package com.shchuangzhi.smartguard.fragment;


import android.content.Context;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.shchuangzhi.smartguard.R;
import com.shchuangzhi.smartguard.core.Consts;
import com.shchuangzhi.smartguard.core.DBHelper;
import com.shchuangzhi.smartguard.core.InOutStats;
import com.shchuangzhi.smartguard.core.Job;
import com.shchuangzhi.smartguard.core.JobManager;
import com.shchuangzhi.smartguard.core.Mode;
import com.shchuangzhi.smartguard.core.Notify;
import com.shchuangzhi.smartguard.core.NotifyMessage;
import com.shchuangzhi.smartguard.core.SyncRecord;

import java.util.List;

import de.codecrafters.tableview.TableView;
import de.codecrafters.tableview.listeners.TableDataClickListener;
import de.codecrafters.tableview.toolkit.SimpleTableDataAdapter;
import de.codecrafters.tableview.toolkit.SimpleTableHeaderAdapter;

/**
 * A simple {@link Fragment} subclass.
 */
public class Stats extends Fragment implements FragmentNamed {
    private DBHelper dbHelper;
    private Handler handler;
    private Context context;
    private String currentKey = ALL_KEY;
    private static final String ALL_KEY = "all";
    private static final String TOTAL_KEY = "[总计]";
    public Stats() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_stats, container, false);
        final TableView<String[]> tv = (TableView<String[]>)view.findViewById(R.id.stats_table_view);
        this.dbHelper = new DBHelper(this.getActivity());
        dbHelper.forceStatsSync();
        InOutStats.getInstance().parse(dbHelper.getStats(1), true);

        setTableView(tv);
        tv.addDataClickListener(new TableDataClickListener<String[]>() {
            @Override
            public void onDataClicked(int rowIndex, String[] clickedData) {
                if (clickedData.length > 0) {
                    if (!clickedData[0].equals(TOTAL_KEY)) {
                        currentKey = currentKey == ALL_KEY ? clickedData[0] : ALL_KEY;
                        setTableView(tv);
                    }
                }
            }
        });

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                setTableView(tv);
            }
        };

        final Job dataSyncJob = JobManager.get(Consts.JOB_DATA_SYNC);
        if (dataSyncJob != null) {
            dataSyncJob.addNotify(Consts.NOTIFY_INOUT_STATS_CHANGED, new Notify() {
                @Override
                public void notify(NotifyMessage message) {
                    handler.sendMessage(handler.obtainMessage(Consts.NOTIFY_INOUT_STATS_CHANGED, message));
                }
            });
        }

        return view;
    }

    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }

    @Override
    public String Name() {
        return Consts.STATS_FRAGMENT_NAME;
    }

    @Override
    public Fragment Fragment() {
        return this;
    }

    private String[][] getViewData(String key, int headerLen) {
        String[][] view = new String[][]{};
        List<InOutStats.InStatsItem> items = InOutStats.getInstance().getInStats(key);
        if (items != null) {
            if (items.size() > 0) {
                view = new String[items.size()][headerLen];
                for(int i = 0; i < items.size(); i++) {
                    for(int j = 0; j < headerLen; j++) {
                        view[i][j] = items.get(i).getValue(j);
                    }
                }
            }
        }
        return view;
    }

    private String[] getHeaderData() {
        String[] headers = new String[]{};
        List<String> list = InOutStats.getInstance().getInStatsHeaders();
        if (list != null) {
            int len = list.size();
            if (len > 0) {
                headers = new String[len];
                for (int i = 0; i < len; i++) {
                    headers[i] = list.get(i);
                }
            }
        }

        return headers;
    }

    private void setTableView(TableView<String[]> tv) {
        String[] headers = getHeaderData();
        if (headers != null && headers.length > 0) {
            tv.setColumnCount(headers.length);
            Context ctx = this.getActivity();
            if (ctx == null) {
                ctx = this.context;
            }
            if (ctx != null) {
                tv.setHeaderAdapter(new SimpleTableHeaderAdapter(ctx, headers));
                tv.setDataAdapter(new SimpleTableDataAdapter(ctx, getViewData(currentKey, headers.length)));
            }
        }
    }
}
